package com.zrfintech.api.aop;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class HttpServletRequestRead extends HttpServletRequestWrapper {

    private byte[] bytes;
    private ServletInputStreamRead servletInputStreamRead;

    public HttpServletRequestRead(HttpServletRequest request) throws IOException {
        super(request);

        InputStream inputStream = request.getInputStream();
        // 读取输入流里的请求参数，并保存到bytes里
        bytes = IOUtils.toByteArray(inputStream);
        this.servletInputStreamRead = new ServletInputStreamRead(new ByteArrayInputStream(bytes));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return servletInputStreamRead;
    }

    public String getRequestParams() throws IOException {
        return new String(bytes, this.getCharacterEncoding());
    }

    private class ServletInputStreamRead extends ServletInputStream {

        private InputStream stream;

        public ServletInputStreamRead(InputStream stream) {
            this.stream = stream;
        }

        @Override
        public int read() throws IOException {
            return stream.read();
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {

        }
    }

}
